package ibms_rcp.db;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import org.eclipse.e4.core.di.annotations.Creatable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class DataBaseManager {
	protected final Logger logger = LoggerFactory.getLogger(DataBaseManager.class);
	private static Connection conn = null;
	private static ResultSet rs;
	private static PreparedStatement ps;
	private static String DRIVERCLASS = "org.postgresql.Driver";
	private static String DATABASE = "jdbc:postgresql://127.0.0.1:5432/m2mnap";
	private static String USERNAME = "postgres";
	private static String PASSWORD = "123456";
	private static int activeCount = 0; //活动连接数
	
    /**
     * 获取数据库连接
     * @return Connection
     */
	public static Connection getConnection() {
		if(conn!=null)
			return conn;
		try {
			Class.forName(DRIVERCLASS);
			System.out.println("加载数据库驱动！！");
//			logger.info("加载数据库驱动！！");
			conn = DriverManager.getConnection(DATABASE, USERNAME, PASSWORD);
//			conn = DriverManager.getConnection("proxool.postgreSQL"); //此处的smms是在proxool.xml中配置的连接池别名
//			this.showPool(); //查看连接池信息
//			logger.info("获得数据库的一个连接！！");
		} catch (Exception e) {
			e.printStackTrace();
//			logger.error(e.getMessage());
//			logger.debug("数据库连接错误！{}",e.getMessage());
		}
		return conn;
	}
	
	/**     
     * 释放连接     
     * freeConnection     
     * @param conn     
     */
	public static void freeConnection(){
        if(conn!=null){
            try {
                conn.close();
                System.out.println("释放数据库连接");
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
	
	public void test(){
		Connection conn = getConnection();
		try {
			String sql = "select * from m2mnap_moc";
			Statement st = conn.createStatement();
			ResultSet rs = st.executeQuery(sql);
			while (rs.next()) {
				System.out.println(rs.getString(1));
			}
			rs.close();
			st.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		freeConnection();
	}
	
	/**
	 * 测试连接
	 * @param args
	 */
	public static void main(String args[]) {
		Connection conn = getConnection();
		try {
			String sql = "select * from m2mnap_moc";
			Statement st = conn.createStatement();
			ResultSet rs = st.executeQuery(sql);
			while (rs.next()) {
				System.out.println(rs.getString(1));
			}
			rs.close();
			st.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		freeConnection();
	}
	
	
}
